<?php


header('Content-type:text');
define("TOKEN", "cfIlWNjt");
require_once $_SERVER['DOCUMENT_ROOT'] . "/weixin/lib/WeChat.php";
require_once $_SERVER['DOCUMENT_ROOT'] . "/weixin/lib/mysql.class.php";
$wechatObj = new wechatCallbackapiTest();
if (!isset($_GET['echostr'])) {
    $wechatObj->responseMsg();
} else {
    $wechatObj->valid();
}

class wechatCallbackapiTest
{
    protected $wxclass;
    protected $db;
    protected $conf = [
        'host' => '127.0.0.1',
        'port' => 3306,
        'user' => 'root',
        'passwd' => 'adasdasdewtrerw',
        'dbname' => 'fastadmin',
        'prefix' => 'jd_wx_'
    ];

    public function __construct()
    {
        $this->wxclass = $wx = new Wechat();
        $this->db = new MMysql($this->conf);
    }

    public function valid()
    {
        $echoStr = $_GET["echostr"];
        if ($this->checkSignature()) {
            echo $echoStr;
            exit;
        }
    }

    private function checkSignature()
    {
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];
        $token = TOKEN;
        $tmpArr = array($token, $timestamp, $nonce);
        sort($tmpArr);
        $tmpStr = implode($tmpArr);
        $tmpStr = sha1($tmpStr);

        if ($tmpStr == $signature) {
            return true;
        } else {
            return false;
        }
    }

    public function responseMsg()
    {
        $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
        if (!empty($postStr)) {
//            $this->logger("R " . $postStr);
            $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
            $RX_TYPE = trim($postObj->MsgType);

            switch ($RX_TYPE) {
                case "event":
                    $result = $this->receiveEvent($postObj);
                    break;
                case "text":
                    $result = $this->receiveText($postObj);
                    break;
            }
//            $this->logger("T " . $result);
            echo $result;
        } else {
            echo "";
            exit;
        }
    }

    //接收文本消息
    private function receiveText($object)
    {
        $keyword = trim($object->Content);
//        $content = date("Y-m-d H:i:s",time())."\n技术支持 方倍工作室";
        $this->addUserInfo($object);
        $userId = $object->FromUserName . '';
        $content = $keyword."<a href='http://jd.ls2346.com/weixin/list.php?&id=$userId'>举报记录</a>";
        ;
//        $this->makePic($object, $keyword);
        if (is_array($content)) {
            if (isset($content[0]['PicUrl'])) {
                $result = $this->transmitNews($object, $content);
            } else if (isset($content['MusicUrl'])) {
                $result = $this->transmitMusic($object, $content);
            }
        } else {
            $result = $this->transmitText($object, $content);
        }

        return $result;
    }

    private function receiveEvent($object)
    {
        $content = "";
        switch ($object->Event) {
            case "subscribe":
                $river_id = (!empty($object->EventKey)) ? str_replace("qrscene_", "", $object->EventKey) : "0";
                $this->addUserInfo($object);
                $userId = $object->FromUserName . '';
                $content =  "<a href='http://jd.ls2346.com/weixin/index.php?river_id=$river_id&id=$userId'>点击举报</a>";
                break;
            case "unsubscribe":
                $content = "取消关注";
                break;
            case 'SCAN':
                $river_id = (!empty($object->EventKey)) ? str_replace("qrscene_", "", $object->EventKey) : "0";
                $this->addUserInfo($object);
                $userId = $object->FromUserName . '';
                $content =  "<a href='http://jd.ls2346.com/weixin/index.php?river_id=$river_id&id=$userId'>点击举报</a>"."<a href='http://jd.ls2346.com/weixin/list.php?&id=$userId'>举报记录</a>";
                break;
            case 'CLICK':
                break;
        }
        $result = $this->transmitText($object, $content);
        return $result;
    }

    private function addUserInfo($object)
    {
        if ($object) {
            $userId = $object->FromUserName . '';
            $userInfo = $this->db->where("open_id='$userId'")->select("users");
            $this->testData($userInfo);
            if (empty($userInfo)) {
                $user = $this->wxclass->get_user_info($this->wxclass->getNormalAccessToken(), $userId);
                $data = array(
                    'open_id' => $userId,
                    'nickName' => $user['nickname'],
                    'avatar' => $user['headimgurl'],
                    'province' => $user['province'],
                    'city' => $user['city'],
                    'create_time' => time(),
                );
                $this->db->insert("users", $data);
            } elseif (!$userInfo[0]['nickname']) {
                $user = $this->wxclass->get_user_info($this->wxclass->getNormalAccessToken(), $userId);
                $data = array(
                    'open_id' => $userId,
                    'nickName' => $user['nickname'],
                    'avatar' => $user['headimgurl'],
                    'province' => $user['province'],
                    'city' => $user['city'],
                    'create_time' => time(),
                );
                $this->db->where("open_id = '$userId'")->update("users", $data);
            }
        }
    }

    //保存数据
    private function testData($data, $name = 'test', $type = 'txt')
    {
        $path = $_SERVER['DOCUMENT_ROOT'] . DIRECTORY_SEPARATOR . 'weixin' . DIRECTORY_SEPARATOR;
        $fp = fopen($path . "$name." . $type, "w");
        fwrite($fp, json_encode($data));
        fclose($fp);
    }


    //制作二维码
    private function makePic($object, $num = 1)
    {
        $userId = $object->FromUserName;
        $imageInfo = $this->wxclass->getImg($num, 2);
        $path = $_SERVER['DOCUMENT_ROOT'] . DIRECTORY_SEPARATOR . 'weixin' . DIRECTORY_SEPARATOR;
        if (!is_dir($path)) {
            @mkdir($path, 0777, 1);
        }
        $filename = $path . $num . "_qr.jpg";

        $local_file = fopen($filename, 'w');

        if (false !== $local_file) {
            if (false !== fwrite($local_file, $imageInfo["body"])) {
                fclose($local_file);
            }
        }
        $media_id = $this->getMId($filename);
        $this->weiXinSend($userId, $media_id, 'image');
    }

    // 发送二维码给用户
    private function weiXinSend($touser, $content, $type)
    {
        $ACC_TOKEN = $this->wxclass->getNormalAccessToken();
        $data = array(
            "touser" => "$touser",
            "msgtype" => "$type",
            "image" => array("media_id" => $content));
        $data = json_encode($data);
        $url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=" . $ACC_TOKEN;

        $result = $this->_https_post($url, $data);
        $final = json_decode($result);
        return $final;
    }

    //上传到微信获得么吊medId
    protected function getMId($filename)
    {
        $ACC_TOKEN = $this->wxclass->getNormalAccessToken();
        $data = array(
            "media" => "@$filename"
        );
        $url = "https://api.weixin.qq.com/cgi-bin/media/upload?access_token=$ACC_TOKEN&type=image";

        $result = $this->https_request($url, $data);
        $final = json_decode($result);
        return $final->media_id;
    }

    private function transmitText($object, $content)
    {
        $textTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[text]]></MsgType>
<Content><![CDATA[%s]]></Content>
</xml>";
        $result = sprintf($textTpl, $object->FromUserName, $object->ToUserName, time(), $content);
        return $result;
    }

    private function transmitNews($object, $arr_item)
    {
        if (!is_array($arr_item))
            return;

        $itemTpl = "    <item>
        <Title><![CDATA[%s]]></Title>
        <Description><![CDATA[%s]]></Description>
        <PicUrl><![CDATA[%s]]></PicUrl>
        <Url><![CDATA[%s]]></Url>
    </item>
";
        $item_str = "";
        foreach ($arr_item as $item)
            $item_str .= sprintf($itemTpl, $item['Title'], $item['Description'], $item['PicUrl'], $item['Url']);

        $newsTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[news]]></MsgType>
<Content><![CDATA[]]></Content>
<ArticleCount>%s</ArticleCount>
<Articles>
$item_str</Articles>
</xml>";

        $result = sprintf($newsTpl, $object->FromUserName, $object->ToUserName, time(), count($arr_item));
        return $result;
    }

    private function transmitMusic($object, $musicArray)
    {
        $itemTpl = "<Music>
    <Title><![CDATA[%s]]></Title>
    <Description><![CDATA[%s]]></Description>
    <MusicUrl><![CDATA[%s]]></MusicUrl>
    <HQMusicUrl><![CDATA[%s]]></HQMusicUrl>
</Music>";

        $item_str = sprintf($itemTpl, $musicArray['Title'], $musicArray['Description'], $musicArray['MusicUrl'], $musicArray['HQMusicUrl']);

        $textTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[music]]></MsgType>
$item_str
</xml>";

        $result = sprintf($textTpl, $object->FromUserName, $object->ToUserName, time());
        return $result;
    }

    private function logger($log_content)
    {
        if (isset($_SERVER['HTTP_APPNAME'])) {   //SAE
            sae_set_display_errors(false);
            sae_debug($log_content);
            sae_set_display_errors(true);
        } else if ($_SERVER['REMOTE_ADDR'] != "127.0.0.1") { //LOCAL
            $max_size = 10000;
            $log_filename = $_SERVER['DOCUMENT_ROOT'] . "/log.xml";

            if (file_exists($log_filename) and (abs(filesize($log_filename)) > $max_size)) {
                unlink($log_filename);
            }
            file_put_contents($log_filename, date('H:i:s') . " " . $log_content . "\r\n", FILE_APPEND);
        }
    }

    //上传文件
    function https_request($url, $data = null)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        if (!empty($data)) {
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_SAFE_UPLOAD, false);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    }

    //url post 请求
    public function _https_post($url, $data)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $result = curl_exec($curl);
        if (curl_errno($curl)) {
            return 'Errno' . curl_error($curl);
        }
        curl_close($curl);
        return $result;
    }
}